//
//  YLAlertView.m
//  yuLink
//
//  Created by 孙强 on 2021/4/8.
//

#import "YLAlertView.h"
#define ANIMATED_ALERT_DURATION 0.27
#define LINE_HEIGHT (1.0/[UIScreen mainScreen].scale)

@interface YLAlertView ()

/** <#注释#> */
@property (nonatomic, strong) UIImageView *bgImageView;
/** <#注释#> */
@property (nonatomic, strong) UIView *alertView;
/** <#注释#> */
@property (nonatomic, strong) NSMutableArray<UIButton *> *btns;

@property (nonatomic, strong) UIButton *dismissBtn;

@property (nonatomic, copy) void (^dismissBlock) (UIButton *sender);
@end

@implementation YLAlertView

#define CONTENT_WIDTH (GJScreenW-108.)
#define LABEL_MAGIN 30.

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        @weakify(self);
        
        self.autoDismiss = YES;
        /** <#注释#> */
        self.bgImageView = [[UIImageView alloc] init];
        [self addSubview:self.bgImageView];
        [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        self.bgImageView.backgroundColor = colorFromHexStringWithAlpha(@"000000", 0.6);
        self.bgImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [self.bgImageView addGestureRecognizer:tap];
        
        self.alertView = [[UIView alloc] init];
        self.alertView.backgroundColor = colorFromHexString(@"2D1D1D");
        ViewBorderRadius(self.alertView, 16, 0, UIColor.whiteColor);
        [self addSubview:self.alertView];
        
        self.contentView = [[UIView alloc] init];
        self.contentView.backgroundColor = UIColor.clearColor;
        
        /** <#注释#> */
        self.titleLabel = [[UILabel alloc] init];
        [self.alertView addSubview:self.titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(15*GJHeight);
            make.left.equalTo(24*GJWidth);
            make.right.equalTo(-56*GJWidth);
            make.height.mas_equalTo(26*GJHeight);
        }];
        _titleLabel.textColor = UIColor.whiteColor;
        _titleLabel.font = [UIFont boldSystemFontOfSize:20*GJHeight];
        _titleLabel.textAlignment = NSTextAlignmentLeft;

        
        self.messageLabel = [[UILabel alloc] init];
        [self.alertView addSubview:self.messageLabel];
        [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.alertView.top).offset(70*GJHeight);
            make.left.equalTo(24*GJWidth);
            make.right.equalTo(-24*GJWidth);
        }];
        _messageLabel.textColor = UIColor.whiteColor;
        _messageLabel.font = [UIFont systemFontOfSize:14*GJHeight];
        _messageLabel.numberOfLines = 0;
        _messageLabel.textAlignment = NSTextAlignmentLeft;


//        [self.alertView addSubview:self.contentView];
//        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.top.equalTo(self.alertView);
//            make.bottom.mas_equalTo(-50);
//        }];
        
        [self.dismissBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleLabel);
            make.right.equalTo(-20);
            make.width.height.mas_equalTo(24);
        }];
    }
    return self;
}
- (void)tap{
    
    if (self.autoDismiss) {
        [self dismiss];
    }
}

+ (YLAlertView *)alertTitle:(NSString *)title cancelAction:(void (^)(UIButton *))cancelBlock {
    YLAlertView *result = [self alertTitle:title message:nil cancelAction:cancelBlock destructionAction:nil];
    return result;
}

+ (YLAlertView *)alertTitle:(NSString *)title message:(NSString *)message destructionAction:(void (^)(UIButton *))destructionBlock {
    YLAlertView *result = [self alertTitle:title message:message cancelAction:nil destructionAction:destructionBlock];
    return result;
}

+ (YLAlertView *)alertTitle:(NSString *)title
                      message:(NSString *)message
                 cancelAction:(void(^)(UIButton *))cancelBlock {
    YLAlertView *result = [self alertTitle:title message:message cancelAction:cancelBlock destructionAction:nil];
    return result;
}

+ (YLAlertView *)alertTitle:(NSString *)title
                      message:(NSString *)message
                 cancelAction:(void(^)(UIButton *))cancelBlock
                   sureAction:(void(^)(UIButton *))sureBlock {
    YLAlertView *result = [self alertTitle:title message:message cancelAction:cancelBlock destructionAction:sureBlock];
    if (sureBlock) {
        [result.destructionBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }
    return result;
}

+ (YLAlertView *)alertTitle:(NSString *)title
                      message:(NSString *)message
                 cancelAction:(void (^)(UIButton *sender))cancelBlock
            destructionAction:(void (^)(UIButton *sender))destructionBlock
                dismissAction:(void (^)(UIButton *sender))dismissActionBlock {
    YLAlertView *result = [self alertTitle:title message:message cancelAction:cancelBlock destructionAction:destructionBlock];
    result.dismissBlock = dismissActionBlock;
    [[result.dismissBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:dismissActionBlock];
    
    if (result.dismissBlock) {
        result.messageLabel.textColor = UIColor.whiteColor;
    }
    return result;
}

+ (YLAlertView *)alertTitle:(NSString *)title
                      message:(NSString *)message
                 cancelAction:(void(^)(UIButton *))cancelBlock
            destructionAction:(void(^)(UIButton *))destructionBlock {
    YLAlertView *result = [[YLAlertView alloc] init];
    result.titleLabel.text = title;
    result.messageLabel.text = message;
    
//    if ([YGUility gjString:title].length>0) {
//        [result.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.top.inset(LABEL_MAGIN);
//            make.centerX.equalTo(result.contentView);
//            make.width.mas_equalTo(CONTENT_WIDTH-2*LABEL_MAGIN);
//        }];
//    }
//    if ([YGUility gjString:message].length>0) {
//        result.messageLabel.text = message;
//        result.messageLabel.numberOfLines = 0;
//        NSMutableAttributedString *attributedString =
//        [[NSMutableAttributedString alloc] initWithAttributedString:result.messageLabel.attributedText];
//        
//        //调整行距
//        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.lineSpacing = 8;
//        paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
//        paragraphStyle.alignment = NSTextAlignmentCenter;
//        [attributedString addAttribute:NSParagraphStyleAttributeName
//                                 value:paragraphStyle
//                                 range:NSMakeRange(0, [result.messageLabel.text length])];
//        result.messageLabel.attributedText = attributedString;
//        
//        [result.messageLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(result.titleLabel.mas_bottom).offset(LABEL_MAGIN);
//            make.centerX.equalTo(result.contentView);
//            make.width.mas_equalTo(CONTENT_WIDTH-2*LABEL_MAGIN);
//            make.bottom.inset(LABEL_MAGIN);
//        }];
//    }
    
    result.btns = [[NSMutableArray alloc] init];
    if (cancelBlock) {
        [[result.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:cancelBlock];
        [result.btns addObject:result.cancelBtn];
    }
    if (destructionBlock) {
        [[result.destructionBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:destructionBlock];
//        [result.destructionBtn setTitleColor:COLOR_MAIN forState:UIControlStateNormal];
        [result.btns addObject:result.destructionBtn];
    }
    if (result.btns.count == 0) {
        @weakify(result);
        result.autoDismiss = YES;
        [result.btns addObject:result.cancelBtn];
    }
    
    if (result.btns.count == 2) {
        [result.btns[0] mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(24*GJWidth);
            make.width.equalTo(143*GJWidth);
            make.height.mas_equalTo(40*GJHeight);
            make.bottom.mas_equalTo(-34*GJHeight);
        }];
        [result.btns[1] mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(-24*GJWidth);
            make.width.equalTo(143*GJWidth);
            make.height.mas_equalTo(40*GJHeight);
            make.bottom.mas_equalTo(-34*GJHeight);
        }];
//        //分割线
//        UIImageView *line = [[UIImageView alloc] init];
//        [result.alertView addSubview:line];
//        [line mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.centerX.equalTo(result.alertView);
//            make.height.mas_equalTo(50);
//            make.width.mas_equalTo(LINE_HEIGHT);
//        }];
//        line.backgroundColor = COLOR_Line_BG;
//        line.contentMode = UIViewContentModeScaleAspectFill;

    } else {
        [result.btns[0] mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(result.alertView);
            make.height.mas_equalTo(50);
        }];
    }
//    //分割线
//    UIImageView *line = [[UIImageView alloc] init];
//    [result.alertView addSubview:line];
//    [line mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.equalTo(result.alertView);
//            make.bottom.mas_equalTo(-49);
//            make.height.mas_equalTo(LINE_HEIGHT);
//    }];
//    line.backgroundColor = COLOR_Line_BG;
//    line.contentMode = UIViewContentModeScaleAspectFill;
    
    return result;
}

- (void)show {
    [KEY_WINDOW addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(KEY_WINDOW);
    }];
    self.bgImageView.alpha = 0;
    [self.alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(343*GJWidth);
        make.height.equalTo(177*GJHeight);
    }];
    self.alertView.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
    [self layoutIfNeeded];
    [UIView animateWithDuration:ANIMATED_ALERT_DURATION delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.bgImageView.alpha = 1.;
        if (self.dismissBlock) {
            self.dismissBtn.hidden = NO;
        } else {
            self.dismissBtn.hidden = YES;
        }
    } completion:^(BOOL finished) {
    }];
    
    [UIView animateWithDuration:ANIMATED_ALERT_DURATION delay:ANIMATED_ALERT_DURATION/2. usingSpringWithDamping:0.5 initialSpringVelocity:25. options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.alertView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
    }];
}

- (void)dismiss {
    [self removeFromSuperview];
}

- (void)resetStatus {
    [self.alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.size.mas_equalTo(CGSizeZero);
    }];
}

#pragma mark - setter && getter
- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        /** <#注释#> */
        @weakify(self);
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.alertView addSubview:_cancelBtn];
        _cancelBtn.titleLabel.font = FONT(14*GJHeight);
        [_cancelBtn addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
        [_cancelBtn setTitleColor:COLOR_MAIN forState:UIControlStateNormal];
        [_cancelBtn setTitle:REAPPString(@"Cancel") forState:UIControlStateNormal];
        
        ViewBorderRadius(_cancelBtn, 4, 1, COLOR_MAIN);
        _cancelBtn.backgroundColor = UIColor.clearColor;
        
    }
    return _cancelBtn;
}

- (UIButton *)destructionBtn {
    if (!_destructionBtn) {
        /** <#注释#> */
        @weakify(self);
        _destructionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.alertView addSubview:_destructionBtn];
        _destructionBtn.titleLabel.font = FONT(14*GJHeight);
        [_destructionBtn addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
        [_destructionBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_destructionBtn setTitle:REAPPString(@"Confirm") forState:UIControlStateNormal];
        ViewBorderRadius(_destructionBtn, 4, 0, COLOR_MAIN);
        _destructionBtn.backgroundColor = COLOR_MAIN;
    }
    return _destructionBtn;
}

- (UIButton *)dismissBtn {
    if (!_dismissBtn) {
        @weakify(self);
        
        _dismissBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.alertView addSubview:_dismissBtn];
        [_dismissBtn addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
        [_dismissBtn setImage:ImageNamed(@"Close") forState:UIControlStateNormal];
        
//        [_dismissBtn ylt_enlargeEdgeWithTop:10 left:10 bottom:10 right:10];
    }
    return _dismissBtn;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
